﻿using System;
using System.Linq;
using System.Runtime.Serialization;

namespace XcoAppSpaces.Serialization.Binary
{
	class ExceptionSerializationSurrogate : ISerializationSurrogate
	{
		public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
		{
			var ex = (Exception)obj;
			info.AddValue("msg", ex.Message);
		}

		public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
		{
			var constructor = info.ObjectType.GetConstructors()
			                      .FirstOrDefault(c => c.GetParameters().Count() == 1 && c.GetParameters().First().ParameterType == typeof(string));
			if (constructor != null)
				return constructor.Invoke(new object[] { info.GetString("msg") });
			else
				return Activator.CreateInstance(info.ObjectType);
		}
	}
}